package com.bw.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.bw.pojo.system.LoginLog;
import com.bw.service.system.LoginLogService;
import com.bw.util.WebUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {
    @Reference
    private LoginLogService loginLogService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {

        System.out.println("登录成功了，我要在这里记录日志");
        String name = authentication.getName();
        String remoteAddr = httpServletRequest.getRemoteAddr();//获取访问的IP
        LoginLog loginLog = new LoginLog();
        loginLog.setLoginName(name);
        loginLog.setIp(remoteAddr);
        loginLog.setLoginTime(new Date());//当前登陆时间
        loginLog.setLocation(WebUtil.getCityByIP(remoteAddr));
        String header = httpServletRequest.getHeader("user-agent");
        loginLog.setBrowserName(WebUtil.getBrowserName(header));
        loginLogService.add(loginLog);


        httpServletRequest.getRequestDispatcher("/main.html").forward(httpServletRequest,httpServletResponse);
    }
}